source ~/.local/bin/ubuild.sh
cd $SCRIPT_FOLDER
source info.ini
REMOTE_PATH=$server_folder/$ROOT/
REMOTE_FOLDER=root@$REMOTE_IP:$server_folder/$ROOT/
nginx_conf=/usr/local/nginx/conf/nginx.conf
#[ -d log ] && rm -rf log
[ ! -d log ] && mkdir log
[ ! -f port ] && echo $RANDOM>port
port=`cat nginx.port`
uwsgi_port=`cat uwsgi.port`
[ ! -f dev.port ] && echo $RANDOM>dev.port
dev_port=`cat dev.port`

env(){
  sudo rm /usr/bin/python
  sudo rm /usr/bin/python3
  sudo rm /usr/local/bin/python
  sudo rm /usr/local/bin/python3
  sudo ln -s /usr/bin/python3.8 /usr/local/bin/python
  sudo ln -s /usr/bin/python3.8 /usr/local/bin/python3
  python3.6 -m pip uninstall pip
  pip uninstall django
  pip install django
  sed -i -r 's/strict=True//g' ~/.local/lib/python3.8/site-packages/django/utils/autoreload.py
  #virtualenv .env
}
log(){
  tail -f log/app.log
}
logger(){
  vi log/app.log
}

dev(){
  <<EOF
  python manage.py makemigrations
  python manage.py migrate
  #port=`cat port`
  #python3 manage.py runserver
EOF
  python3 $SCRIPT_FOLDER/manage.py runserver 0.0.0.0:$dev_port |tee log/app.log
}
vanish(){
  pid_list=("dev.pid")
  for i in ${pid_list[@]};do
    if [ -f $i ];then
      pid=`cat $i`
      if [ ! -z "$pid" ] && [ ! "$pid" = 0 ];then
        sudo kill -9 "$pid"
      fi
    fi
  done
  ps -ef | grep $ROOT|grep --invert-match "grep\|$SCRIPT"| awk '{print $2}' | xargs -r sudo kill
  sleep 4
  ps -ef | grep $ROOT
}

dev_nohup(){
 shutdown 
  #python3 manage.py runserver
  nohup python3 $SCRIPT_FOLDER/manage.py runserver 0.0.0.0:$dev_port >log/app.log 2>&1 &
  echo $!>dev.pid
  disown
}

dos2unix(){
  vim -c 'set ff=unix' -c 'wq' port
}

shutdown(){

  if [ `uname` = "Darwin" ];then :
  else
    xargs_opt=-r
  fi

  pid_list=("dev.pid" "pid" "uwsgi.pid")
  for i in ${pid_list[@]};do
    if [ -f $i ];then
      pid=`cat $i`
      if [ ! -z "$pid" ] && [ ! "$pid" = 0 ];then
        sudo kill -9 "$pid"
      fi
    fi
  done
  ps -ef | grep $ROOT|grep --invert-match "grep\|$SCRIPT"| awk '{print $2}' | xargs -r sudo kill

  sudo systemctl stop nginx
  sudo systemctl disable nginx
  ps -ef | grep $ROOT|grep --invert-match "grep\|$SCRIPT"| awk '{print $2}' | xargs $xargs_opt sudo kill

  [ -f uwsgi.pid ] && uwsgi --stop $SCRIPT_FOLDER/uwsgi.pid
  if [ `uname` = "Darwin" ];then
    launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist
  else
    sudo systemctl stop nginx
    sudo systemctl disable nginx
  fi
}

reboot(){
  uwsgi --reload uwsgi.pid
}

debug_nohup(){
  shutdown

  port=`cat port`
  chmod +x debug.sh
  nohup $PWD/debug.sh >/dev/null 2>&1 &
  PID=$!
  echo "${PID}">pid
}

boot(){
  port=`cat uwsgi.port`
  uwsgi --http :$port --wsgi-file $ROOT/wsgi.py
}

daemon(){
  nginx_conf
  uwsgi_ini

  shutdown
  #sleep 4

  sudo systemctl restart nginx
  #sudo systemctl status nginx

  #cd $ROOT
  #python3 manage.py makemigrations
  #python3 manage.py migrate
  #cd ..
  uwsgi --ini $SCRIPT_FOLDER/uwsgi.ini | tee log/$RANDOM
  echo $!>pid

  sleep 4
  status
  xdg-open http://localhost:$port
}

index(){
  url=http://localhost:$port
  if [ `uname` = "Darwin" ];then open $url; return;fi
  xdg-open $url
}

login(){
  sshpass -p $REMOTE_PASSWORD ssh -o StrictHostKeyChecking=no root@$REMOTE_IP
}

ls_remote(){
  mkdir -p log
  ssh root@$REMOTE_IP 2>&1 <<EOF | tee ./log/$RANDOM 
set -x
cd $REMOTE_PATH
ls -l
exit
EOF
}

nopass_conf(){
  # ssh-keygen -t rsa
  sshpass -p $REMOTE_PASSWORD ssh root@$REMOTE_IP mkdir -p .ssh
  cat ~/.ssh/id_rsa.pub | sshpass -p $REMOTE_PASSWORD ssh root@$REMOTE_IP 'cat >> ~/.ssh/authorized_keys'
}

install(){
  <<EOF
  #sudo pacman -S sshpass
  #sudo pacman -Syu
  #sudo pacman -S nginx
  pip3 install uwsgi
  #uwsgi --version
  #uwsgi --python-version
  python -m pip install --upgrade pip
  pip3 install Django==3.0.6 -i https://pypi.tuna.tsinghua.edu.cn/simple
  pip3 install django-oauth-toolkit
  #python manage.py startapp users
  python3 manage.py check
  python3 manage.py makemigrations
  python3 manage.py migrate
EOF
}
swagger_conf(){
  pip install -U drf-yasg

  conf=$ROOT/settings.py
  if ! grep --quiet 'drf_yasg' $conf;then
    file=`basename -- $conf`
    cp -f $conf log/$file-`date +"%Y%m%d-%H%M%S"`
    sed -i -r '/INSTALLED_APPS\s+=/ r /dev/stdin' $conf<<EOF
    'django.contrib.staticfiles',  # required for serving swagger ui's css/js files
    'drf_yasg',
EOF
  fi
}
uninstall_swagger_deprecated(){

  pip uninstall django-rest-swagger
  pip2 uninstall django-rest-swagger

  conf=$ROOT/settings.py
  if grep --quiet 'rest_framework_swagger' $conf;then
    file=`basename -- $conf`
    cp -f $conf log/$file-`date +"%Y%m%d-%H%M%S"`
    sed -i -r '/rest_framework_swagger/d' $conf
  fi
}
install_swagger_deprecated(){
  pip uninstall pathlib
  pip2 uninstall django-rest-swagger
  pip install --user django-rest-swagger
  #assert_error $!

  conf=$ROOT/settings.py
  if ! grep --quiet 'rest_framework_swagger' $conf;then
    file=`basename -- $conf`
    cp -f $conf log/$file-`date +"%Y%m%d-%H%M%S"`
    #sed -i -r "/INSTALLED_APPS\s+=/ a 'rest_framework_swagger'," $conf
    sed -i -r '/INSTALLED_APPS\s+=/ r /dev/stdin' $conf<<EOF
    'rest_framework_swagger',
EOF
  fi
  
}

admin(){
  python manage.py createsuperuser
  [ ! -f password ] && echo $RANDOM>password
  password=`cat password`
  <<EOF
iwill
junehwang0@gmail.com
$password
EOF
}

schema(){
  #python manage.py migrate oauth2_provider
  python manage.py makemigrations
  python manage.py migrate
}

fix_schema(){
  python manage.py dbshell
  cat <<EOF 
  .tables
  select * from django_migrations where app='xxx';
  delete from django_migrations where id in (xxx,xxx);
  drop table xxx;
  .quit
EOF

}

status(){
  if [ ! `uname` = "Darwin" ];then
    sudo systemctl status nginx
  fi
  ps -ef|grep --invert-match "grep\|$SCRIPT"|grep uwsgi
  ps -ef|grep --invert-match "grep\|$SCRIPT"|grep $ROOT
  ps -ef|grep --invert-match "grep\|$SCRIPT"|grep python
}

nginx_conf(){

  if grep --quiet $SCRIPT_FOLDER $nginx_conf;then
    return 0
  fi
  cat >nginx.conf<<EOF
server {

   listen $port;

   server_name 127.0.0.1 localhost;
   #access_log $SCRIPT_FOLDER/log/access.log;
   #error_log $SCRIPT_FOLDER/log/error.log;

   location ^~ /static/ {
      root $SCRIPT_FOLDER;
   }

   location / {
      include uwsgi_params;
      uwsgi_pass 127.0.0.1:$uwsgi_port;
   }
}
EOF
  cp $nginx_conf log/nginx.conf-`date +'%F-%T'`
  sudo sed -i -r "/http\s+/a include $SCRIPT_FOLDER/nginx.conf;" $nginx_conf

}

publish(){
  port=`cat port`
  mkdir log
  #tar vczf ./log/$ROOT.tar.gz $ROOT

  ssh root@$REMOTE_IP <<EOF
mkdir -p $REMOTE_PATH
exit
EOF

nginx_conf

files=(
  #"build.sh" \
  "install.sh" \
    "port" \
    #"./log/$ROOT.tar.gz" \
  )
  for i in "${files[@]}"
  do
    scp $i $REMOTE_FOLDER
  done

  ssh root@$REMOTE_IP <<EOF 2>&1 | tee ./log/$RANDOM
cd $REMOTE_PATH
#tar vxzf $ROOT.tar.gz
#bash install.sh
bash build.sh daemon
disown
exit
EOF
}

uwsgi_ini(){
  uwsgi_port=`cat uwsgi.port`
  cat >uwsgi.ini<<EOF
[uwsgi]
socket=127.0.0.1:$uwsgi_port
chmod-socket=777
chdir=$SCRIPT_FOLDER
module=$ROOT.wsgi:application
master=True
processes=4
pidfile=$SCRIPT_FOLDER/uwsgi.pid
vacuum=True
max-requests=4096
buffer-size=65536
daemonize=$SCRIPT_FOLDER/log/uwsgi.log
EOF
}

$@
cd $CD
